#include <iostream>
#include <string>
#include <unistd.h>
#include <functional>
#include <memory>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#include <cstring>
#include <cstdio>
#include <set>
#include "Log.hpp"
#include "InetAddr.hpp"
#include "ThreadPool.hpp"


class Command
{
public:

	std::string Excute(const std::string& cmd)
	{
		FILE* stream = popen(cmd.c_str(),"r");		
		std::string result;
		if(stream)
		{
			char line[1024];
			while(fgets(line,sizeof(line),stream))
			{
				result += line;
			}
			return result.empty()?"success" : result;
		}
		pclose(stream);
		return "excute error";
	}

	void Handler(int sockfd,InetAddr& addr)
	{
		while (true)
        {
            char inbuff[1024];
            int n = ::recv(sockfd, inbuff, sizeof(inbuff) - 1,0);
            if (n > 0)
            {
                inbuff[n] = 0;
				std::string result;
				result += Excute(inbuff);
                ::send(sockfd,result.c_str(),result.size(),0);
            }
            else if (n == 0)
            {
                LOG(INFO, "[%s] quit\n",addr.AddrStr().c_str());
                break;
            }
            else
            {
                LOG(ERROR, "server read %s error\n",addr.AddrStr().c_str());
                break;
            }
        }
	}

};
